package com.yupi.springbootinit.model.dto.chart;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.yupi.springbootinit.model.dto.chart.ChartEsDTO;
import com.yupi.springbootinit.model.entity.Chart;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.util.Date;
import java.util.List;


@Data
public class ChartEsDTO {
    private static final String DATE_TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    
    /**
     * id
     */
    @Id
    private Long id;
    
    /**
     * 标题
     */
    private String title;
    
    /**
     * 内容
     */
    private String content;
    
    /**
     * 标签列表
     */
    private List<String> tags;
    
    /**
     * 点赞数
     */
    private Integer thumbNum;
    
    /**
     * 收藏数
     */
    private Integer favourNum;
    
    /**
     * 创建用户 id
     */
    private Long userId;
    
    /**
     * 创建时间
     */
    @Field(index = false, store = true, type = FieldType.Date, format = {}, pattern = DATE_TIME_PATTERN)
    private Date createTime;
    
    /**
     * 更新时间
     */
    @Field(index = false, store = true, type = FieldType.Date, format = {}, pattern = DATE_TIME_PATTERN)
    private Date updateTime;
    
    /**
     * 是否删除
     */
    private Integer isDelete;
    
    private static final long serialVersionUID = 1L;
    
    /**
     * 对象转包装类
     *
     * @param chart
     * @return
     */
    public static ChartEsDTO objToDto(Chart chart) {
        if (chart == null) {
            return null;
        }
        ChartEsDTO chartEsDTO = new ChartEsDTO();
        BeanUtils.copyProperties(chart, chartEsDTO);
        String tagsStr = chart.getChartData();
        if (StringUtils.isNotBlank(tagsStr)) {
            chartEsDTO.setTags(JSONUtil.toList(tagsStr, String.class));
        }
        return chartEsDTO;
    }
    
    /**
     * 包装类转对象
     *
     * @param chartEsDTO
     * @return
     */
    public static Chart dtoToObj(ChartEsDTO chartEsDTO) {
        if (chartEsDTO == null) {
            return null;
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEsDTO, chart);
        List<String> tagList = chartEsDTO.getTags();
        if (CollUtil.isNotEmpty(tagList)) {
            chart.setChartData(JSONUtil.toJsonStr(tagList));
        }
        return chart;
    }
}
